package com.sau.pixelcart.service.impl;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sau.pixelcart.common.constant.OrderConstant;
import com.sau.pixelcart.common.result.Result;
import com.sau.pixelcart.domain.entity.InventoryAdjustment;
import com.sau.pixelcart.domain.entity.Orders;
import com.sau.pixelcart.domain.entity.ProductInventory;
import com.sau.pixelcart.domain.vo.*;
import com.sau.pixelcart.mapper.InventoryAdjustmentMapper;
import com.sau.pixelcart.mapper.OrdersMapper;
import com.sau.pixelcart.mapper.ProductInventoryMapper;
import com.sau.pixelcart.mapper.UserMapper;
import com.sau.pixelcart.service.DashboardService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductInventoryMapper productInventoryMapper;
    @Autowired
    private InventoryAdjustmentMapper inventoryAdjustmentMapper;
    @Autowired
    private OrdersServiceImpl ordersServiceImpl;

    public DashboardServiceImpl(OrdersMapper ordersMapper) {
        this.ordersMapper = ordersMapper;
    }

    /**
     * 首页看板
     */
    @Override
    public DashboardVO dashboardView() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //1. 顶部四个模块
        LocalDate endDate = LocalDate.now().plusDays(1);
        LocalDate beginDate = endDate.minusDays(30);

        //订单表30日内，合计销售额
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.gt(Orders::getCreateTime,beginDate);
        ordersLambdaQueryWrapper.le(Orders::getCreateTime,endDate);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getCreateTime);
        //查订单表30日内订单数据
        List<Orders> orderList = ordersMapper.selectList(ordersLambdaQueryWrapper);

        //合计销售额
        BigDecimal totalSalesPrice = BigDecimal.ZERO;
        for (Orders order : orderList) {
            totalSalesPrice = totalSalesPrice.add(order.getPrice());
        }
        //合计订单数
        int totalOrders = orderList.size();

        //查库存表
        LambdaQueryWrapper<ProductInventory> productInventoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<ProductInventory> productInventoryList = productInventoryMapper.selectList(productInventoryLambdaQueryWrapper);
        int totalStockNumber = 0;
        for (ProductInventory productInventory : productInventoryList) {
            //合计库存
            totalStockNumber = totalStockNumber + productInventory.getStock();
        }

        //查库存记录表
        LambdaQueryWrapper<InventoryAdjustment> inventoryAdjustmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        inventoryAdjustmentLambdaQueryWrapper.gt(InventoryAdjustment::getAdjustmentTime,beginDate);
        inventoryAdjustmentLambdaQueryWrapper.le(InventoryAdjustment::getAdjustmentTime,endDate);
        List<InventoryAdjustment> inventoryAdjustmentList = inventoryAdjustmentMapper.selectList(inventoryAdjustmentLambdaQueryWrapper);
        int totalInStock = 0;
        int totalOutStock = 0;
        for (InventoryAdjustment inventoryAdjustment : inventoryAdjustmentList) {
            if(inventoryAdjustment.getReason().equals("inStock")){
                //入库
                int updateStock = inventoryAdjustment.getNewStock() - inventoryAdjustment.getOldStock();
                totalInStock = totalInStock + updateStock;
            }
            if(inventoryAdjustment.getReason().equals("outStock")){
                //出库
                int updateStock = inventoryAdjustment.getOldStock() - inventoryAdjustment.getNewStock();
                totalOutStock = totalOutStock + updateStock;
            }
        }
        // 计算出库比例
        BigDecimal ratio = BigDecimal.ZERO;
        if(totalInStock != 0 && totalOutStock != 0){
            ratio = BigDecimal.valueOf(totalOutStock)
                    .divide(BigDecimal.valueOf(totalInStock), 4, RoundingMode.HALF_UP);
        }
        // 转换为百分比
        BigDecimal amountPercentage = ratio.multiply(BigDecimal.valueOf(100));

        //四个模块
        DashboardSaleVO dashboardSaleVO = DashboardSaleVO.builder()
                .totalSalesPrice(totalSalesPrice)
                .totalOrders(totalOrders)
                .totalInStock(totalInStock)
                .totalOutStock(totalOutStock)
                .totalStockNumber(totalStockNumber)
                .amountPercentage(amountPercentage)
                .build();

        //2. 最近七日折线图
        //查折线图
        LocalDate zheXianBeginDate = endDate.minusDays(7);
        List<SalesTrendVO> salesTrendDateList = ordersServiceImpl.getSalesTrendDateList(zheXianBeginDate, endDate, orderList);

        //3. 饼图
        List<CategorySalesVO> categorySaleList = ordersServiceImpl.getCategorySales(beginDate, endDate);

        //4. 最近两个订单
        List<Orders> nearlyOrders = new ArrayList<>();
        // 计算可以安全获取的元素数量（不超过2个）
        int count = Math.min(2, orderList.size());
        for (int i = 0; i < count; i++) {
            nearlyOrders.add(orderList.get(i));
        }

        //最近两个订单
        List<OrderVO> nearlyOrderVOList = nearlyOrders.stream().map(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOperatorName(userMapper.selectById(orders.getOperatorId()).getUsername());
            return orderVO;
        }).collect(Collectors.toList());

        return DashboardVO.builder()
                .dashboardSaleVO(dashboardSaleVO)
                .categorySalesVO(categorySaleList)
                .salesTrendVO(salesTrendDateList)
                .orderVOList(nearlyOrderVOList)
                .build();

    }
}
